﻿using log4net.Core;
using System.Collections.ObjectModel;
using System.Windows;
using System.Collections.Generic;
using System;

namespace HobSoft.SoccerBet2014.Client.Common
{
    using Domain.Implementation;
    using Domain.Models.Site;
    using Domain.Models;

    public class BetApplication : Application
    {
        private readonly ObservableCollection<LoggingEvent> _applicationLogs;
        public ReadOnlyObservableCollection<LoggingEvent> ApplicationLogs
        {
            get;
            protected set;
        }
        public BetApplication()
        {
            _applicationLogs = new ObservableCollection<LoggingEvent>();
            ApplicationLogs = new ReadOnlyObservableCollection<LoggingEvent>(_applicationLogs);
            SoccerBet2014.Common.Wpf.Behavior.DataGridContextHelper.Initialize();
        }

        protected void Application_Startup(object sender, StartupEventArgs e)
        {
            AutoMapper.Mapper.Initialize(c =>
            {
                c.AddProfile<ModelsMapper.ModelMapperConfiguration>();
            });
            Log.ApplicationCacheLogAppender.Register();
            Log.ApplicationCacheLogAppender.Singleton.AddCacheCollection(_applicationLogs, 60, lg => true);

            InitializeAllCacheModels();
        }

        static BetApplication()
        {
            cacheSubmitProxy.Add(typeof(Bookmaker), () => BinaryContext.Current.Submit<Bookmaker, byte>());
            cacheSubmitProxy.Add(typeof(BmAccount), () => BinaryContext.Current.Submit<BmAccount, string>());
            cacheSubmitProxy.Add(typeof(BFAccount), () => BinaryContext.Current.Submit<BFAccount, string>());
            cacheSubmitProxy.Add(typeof(AccountCookie), () => BinaryContext.Current.Submit<AccountCookie, long>());
            cacheSubmitProxy.Add(typeof(SiteContext), () => BinaryContext.Current.Submit<SiteContext, string>());
        }
        static Dictionary<Type, Action> cacheSubmitProxy = new Dictionary<Type, Action>();

        public static void InitializeAllCacheModels()
        {
            BinaryContext.Current.Initialize<Bookmaker, byte>();
            BinaryContext.Current.Initialize<BmAccount, string>();
            BinaryContext.Current.Initialize<BFAccount, string>();
            BinaryContext.Current.Initialize<AccountCookie, long>();
            BinaryContext.Current.Initialize<SiteContext, string>();
        }

        public static void SubmitCacheModel<T>()
        {
            var type = typeof(T);
            if (cacheSubmitProxy.ContainsKey(type))
            {
                cacheSubmitProxy[type]();
            }
        }
    }
}
